package juc.completablefuture.methods.or;

/**
 * @ClassName ApplyToEitherExample
 * @PackageName completablefuture.methods.or
 * @projectName myThread
 * @Description 
 * @Author games
 * @Date 2025/8/27 下午5:15
 * @Version 1.0
 */

import java.util.concurrent.CompletableFuture;

/**
 * 1. applyToEither()
 * 作用：两个任务谁执行的快，就使用那一个结果，有返回值。
 * 返回值：一个新的 CompletableFuture，其结果是较快完成任务的输出。
 */
public class ApplyToEitherExample {
    public static void main(String[] args) {
        CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> {
            String threadName = Thread.currentThread().getName();
            System.out.println("Slow Task started by thread: " + threadName);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Slow Task from thread: " + threadName;
        });

        CompletableFuture<String> cf2 = CompletableFuture.supplyAsync(() -> {
            String threadName = Thread.currentThread().getName();
            System.out.println("Fast Task started by thread: " + threadName);
            return "Fast Task from thread: " + threadName;
        });

        CompletableFuture<String> eitherCF = cf1.applyToEither(cf2, result -> result);

        eitherCF.thenAccept(result -> {
            String threadName = Thread.currentThread().getName();
            System.out.println("ApplyToEitherExample started by thread: " + threadName);
            System.out.println("Result: " + result );
        });

    }
}
